package com.shimakaze.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shimakaze.reggie.common.CustomException;
import com.shimakaze.reggie.dto.DishDto;
import com.shimakaze.reggie.entity.Dish;
import com.shimakaze.reggie.entity.DishFlavor;
import com.shimakaze.reggie.entity.Setmeal;
import com.shimakaze.reggie.entity.SetmealDish;
import com.shimakaze.reggie.mapper.DishMapper;
import com.shimakaze.reggie.service.DishFlavorService;
import com.shimakaze.reggie.service.DishService;
import com.shimakaze.reggie.service.SetmealDishService;
import com.shimakaze.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增菜品，同时保存对应的口味信息
     * @param dishDto
     */
    @Transactional
    //操作两张表需要开启事务管理
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品的基本信息到dish
        this.save(dishDto);

        //获取菜品id
        Long dishId = dishDto.getId();

        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        //类似for循环
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());

        //保存菜品的口味数据到dish_flavor
        dishFlavorService.saveBatch(flavors);
    }


    /**
     * 根据id查询菜品信息和口味，需要操作两张表：dish、dish_flavor
     * @param id
     * @return
     */
    //查询不需要开启事务管理
    public DishDto getByIdWithFlavor(Long id) {
        //从dish表查询菜品基本信息
        Dish dish = this.getById(id);

        if(dish != null){
            //将菜品基本信息（即dish）拷贝到dishDto
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);

            //从dish_flavor查询菜品口味信息
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> flavorList = dishFlavorService.list(lambdaQueryWrapper);

            dishDto.setFlavors(flavorList);

            return dishDto ;
        }
        return null;
    }

    /**
     * 修改菜品信息，需要操作两张表：dish、dish_flavor
     * @param dishDto
     */
    @Transactional
    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //修改菜品: dish表基本信息
        this.updateById(dishDto);

        /**
         * 更新dish_flavor表
         * 先删除口味集合 : dish_flavor表的delete操作
         * 再添加提交过来的口味集合 : dish_flavor表的insert操作
         */
        //删除
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(lambdaQueryWrapper);
        //添加,还要添加dishId
        List<DishFlavor> flavorList = dishDto.getFlavors();
        flavorList = flavorList.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavorList);

    }

    /**
     * 批量删除菜品，同时删除菜品关联口味信息
     * 同时删除dish、dish_flavor 两张表
     * @param ids
     */
    @Transactional
    @Override
    public void removeByIdWithFlavor(List<Long> ids) {
        //如果菜品正在售卖或已关联套餐则抛出业务异常
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getDishId,ids);
        int countWithSetmeal = setmealDishService.count(setmealDishLambdaQueryWrapper);

        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.in(Dish::getId,ids).eq(Dish::getStatus,1);
        int countSelling = this.count(dishLambdaQueryWrapper);

        log.info("countWithSetmeal:   " + String.valueOf(countWithSetmeal));
        log.info("countSelling:   " + String.valueOf(countSelling));

        if(countWithSetmeal > 0 || countSelling > 0){
            throw new CustomException("启售菜品或已关联套餐的菜品无法删除");
        }

        //先删除菜品和口味的关联信息 dish_flavor
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.in(DishFlavor::getDishId,ids);
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);

        //再删除菜品 dish
        this.removeByIds(ids);

    }


    /**
     * 批量修改菜品状态
     * 如果一个菜品被停售，那么其关联的所有套餐都必须停售
     * @param status
     * @param ids
     */
    @Transactional
    @Override
    public void updateStatus(int status, List<Long> ids) {
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.in(ids!=null,Dish::getId,ids);
        Dish dish = new Dish();
        dish.setStatus(status);
        this.update(dish,dishLambdaQueryWrapper);

        //如果一个菜品被停售，那么其关联的所有套餐都必须停售
        if(status == 0){
            LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            setmealDishLambdaQueryWrapper.in(SetmealDish::getDishId,ids);

            List<SetmealDish> setmealDishList = setmealDishService.list(setmealDishLambdaQueryWrapper);

/*            for(SetmealDish setmealDish : setmealDishList){
                Long dishId = setmealDish.getDishId();
                Dish dish = dishService.getById(dishId);
                dish.setStatus(1);
                dishService.updateById(dish);
            }*/

            setmealDishList.stream().map((item) -> {
                Long setmealId = item.getSetmealId();
                Setmeal setmeal = setmealService.getById(setmealId);
                setmeal.setStatus(0);
                setmealService.updateById(setmeal);

                return setmealDishList;

            }).collect(Collectors.toList());
        }

    }

}
